<template>
  <div class="costForm">
    <group label-width="1rem" label-align="left" gutter="0">
      <x-input title="科目" ref="subjectName" @on-focus="choiceSubject" :required="true" v-model="formdata.subjectName" :show-clear="false">
      </x-input>
      <template v-for="(item,index) in formdata.subjectList">
        <x-input v-if="item.type === 'input'" :title="item.label" :required="item.required"
                 v-model="formdata.subjectContent[item.key]"
                 :key="index"></x-input>
        <x-textarea v-if="item.type === 'textarea'" :title="item.label" :required="item.required"
                    v-model="formdata.subjectContent[item.key]"
                    :max="140" :key="index">
        </x-textarea>
        <selector v-if="item.type === 'select'" :value-map="['code','name']" :required="item.required"
                  :title="item.label"
                  v-model="formdata.subjectContent[item.key]" :options="formdata.subjectSelect[item.dict||item.key]"
                  :key="index"></selector>
        <!--<Autocomplete v-if="item.type === 'region'" placeholder="请输入" :required="item.required" :title="item.label"-->
        <!--url="/expense/api/region"-->
        <!--v-model="formdata.subjectContent[item.key]"></Autocomplete>-->
        <x-input v-if="item.type === 'region'" :title="item.label" @on-focus="()=>{choiceCity(item.key)}"  :show-clear="false"
                 v-model="formdata.subjectContent[item.key]">
        </x-input>
        <x-input v-if="item.type === 'disable'" :title="item.label" v-model="formdata.subjectContent[item.key]"
                 :key="index" :disabled="true"></x-input>
        <x-input v-if="item.type === 'location'" :title="item.label" :required="item.required"   :show-clear="false"
                 v-model="formdata.subjectContent[item.key]"
                 :key="index" @on-focus="()=>{choiceLocation(item.key)}" placeholder="请输入">
        </x-input>
      </template>
      <x-input title="报销数量" ref="count" v-model="formdata.count" :required="true" placeholder="请输入"></x-input>
      <x-input title="报销金额" ref="fillFigure" @on-blur="getAccount" v-model="formdata.fillFigure"
               placeholder="¥" :required="true"></x-input>
      <x-textarea title="费用说明" v-model="formdata.state" :max="140" placeholder="请输入">
      </x-textarea>
      <cell title="发票拍照" is-link @click.native="showPopup(formdata.invoiceFileStore,'发票拍照')">
        <span slot="child" class="child">{{formdata.invoiceFileStore.length}}张图片</span>
        <img slot="after-title" width="20" style="margin-right:5px;"
             src="~assets/images2/icon_shangchuan@3x.png"/>
      </cell>
      <cell title="支付凭证" is-link @click.native="showPopup(formdata.voucherFileStore,'支付凭证')">
        <span slot="child" class="child">{{formdata.voucherFileStore.length}}张图片</span>
        <img slot="after-title" width="20" style="margin-right:5px;"
             src="~assets/images2/icon_shangchuan@3x.png"/>
      </cell>
    </group>
    <div v-transfer-dom>
      <popup v-model="showSubject"height="90%">
        <!--<popup-header-->
          <!--:left-text="cancel"-->
          <!--:right-text="done"-->
          <!--title="选择报销科目"-->
          <!--:show-bottom-border="false"-->
          <!--@on-click-left="superior"-->
          <!--@on-click-right="subordinate"></popup-header>-->
        <!--<group gutter="0" style="overflow:auto;height: calc(100% - 44px);width: 100%;">-->
          <!--<Tree :model="subjectTree" v-on:checkSubject="checkSubject" style="padding: 10px;overflow:auto"></Tree>-->
        <!--</group>-->
        <subjectSelect style="height:100%;width: 100%;" v-on:checkSubject="checkSureSubject"></subjectSelect>
      </popup>
    </div>
    <div v-transfer-dom>
      <popup v-model="showMap" height="90%">
        <popup-header
          :left-text="cancel"
          :right-text="done"
          title="选择位置"
          :show-bottom-border="false"
          @on-click-left="cancelMap"
          @on-click-right="sureMap"></popup-header>
        <x-input  @on-change="searchSure(search)" :debounce="100" @on-enter="searchSure" class="weui-vcode" v-model="search" placeholder="输入地址">
          <i slot="label" style="margin-right: 10px" class="fa fa-map-marker"></i>
          <!--<i slot="right" @click="searchSure(search)" class="fa fa-search"></i>-->
        </x-input>
        <div :id="'container'+current" style="height: calc(100% - 82px);width: 100%;"></div>
      </popup>
    </div>
    <div v-transfer-dom>
      <popup v-model="bxdPopup"height="90%">
        <popup-header
          left-text="取消"
          right-text="确认"
          :title="popupPicTitle"
          :show-bottom-border="false"
          @on-click-left="showPopup"
          @on-click-right="showPopup"></popup-header>
        <UploadImage :imgs="reimbursementImg"></UploadImage>
      </popup>
    </div>
    <div v-transfer-dom>
      <popup v-model="showCity" height="90%">
        <!--<popup-header-->
          <!--:left-text="cancel"-->
          <!--:right-text="done"-->
          <!--title="选择城市"-->
          <!--:show-bottom-border="false"-->
          <!--@on-click-left="superiorCity"-->
          <!--@on-click-right="subordinateCity"></popup-header>-->
        <SelectTree style="height:100%;width: 100%;" v-on:checkCity="subordinateCity"></SelectTree>
        <!--<x-input @on-enter="searchCityHandle" class="weui-vcode" v-model="searchCity" placeholder="输入地址">-->
          <!--<i slot="label" style="margin-right: 10px" class="fa fa-search"></i>-->
          <!--<i slot="right" @click="searchCityHandle(searchCity)" class="fa fa-search"></i>-->
        <!--</x-input>-->
        <!--<group gutter="0" style="background:#FFFFFF;overflow:auto;height: calc(100% - 82px);width: 100%;">-->
          <!--<AsynTree v-if="searchCity ==''||searchCity==null" :model="cityTree" v-on:checkCity="checkCity"-->
                    <!--style="padding: 0 10px 10px;overflow:auto;height: 100%;"></AsynTree>-->
          <!--<ul v-else="searchCity ==''||searchCity==null"-->
              <!--style="padding: 0 10px 10px;overflow:auto;height: 100%;">-->
            <!--<li v-for="(item, index) in cityList">-->
              <!--<div :class="{checked:item.checked}">-->
                <!--<span class="itemDiv">-->
                <!--<span @click="clickCity(item,index)">{{ item.mergerName }}</span>-->
                <!--<i class="fa fa-check" v-if="item.checked" style="float: right"></i>-->
                <!--</span>-->
              <!--</div>-->
            <!--</li>-->
          <!--</ul>-->
        <!--</group>-->
      </popup>
    </div>
  </div>
</template>
<script>
  import {
    Group, XInput, XTextarea, Selector, Cell, Icon, XButton, PopupHeader, Popup, TransferDom, Radio, PopupPicker
  } from 'vux'
  import UploadImage from './uploadImage.vue'
  import Autocomplete from './Autocomplete.vue'
  import SelectTree from './SelectTree.vue'
  import subjectSelect from './subjectSelect.vue'
  import AMap from 'AMap'
  import AMapUI from 'AMapUI'
  import icon from "@/assets/images/mark_b.png"

  export default {
    name: "create",
    props: ['formdata', 'current', 'exitRequestList'],
    directives: {
      TransferDom
    },
    components: {
      Group,
      XInput,
      XTextarea,
      Selector,
      Cell,
      Icon,
      XButton,
      PopupHeader,
      Popup,
      Radio,
      UploadImage,
      Autocomplete,
      SelectTree,
      PopupPicker,
      subjectSelect
    },
    data() {
      return {
        // form: this.formdata,
        showSubject: false,
        showRegion: false,
        showMap: false,
        showCity: false,
        cancel: '取消',
        done: '确定',
        bxdPopup: false,//图片上传弹窗
        subjectTree: [],//报销科目树形图
        cityTree: [],//城市树形图
        reimbursementImg: [],//当前图片列表
        popupPicTitle:'',//弹出界面显示
        search: '',//地址搜索,
        searchCity: '',//城市搜索
        cityList: [],
        lnglat: {},
      }
    },
    created() {

    },
    mounted() {
      //初始化定位函数
      this.geocoder = new AMap.Geocoder({});
      //存储位置信息
      this.lnglatSure = {}
    },
    methods: {
      // //设置城市等级
      // setCityLevel(data){
      //   this.formdata.subjectContent['cityLevel'] = data.level;
      // },
      //
      //城市列表中选择
      clickCity(item, index) {
        this.cityList.forEach((r, ind) => {
          if (index == ind)
            r.checked = !r.checked;
          else
            r.checked = false;
        });
        this.currentCity = {item: item};
      },
      // 搜索城市列表
      searchCityHandle() {
        this.$http.get("/account/api/region", {
          params: {
            mergerNameSplit: this.searchCity,
            include: true,
            pageSize: 20,
            levelSort: 'desc',
            fields: 'mergerName,level'
          }
        }).then(res => {
          if (res.data.data) {
            res.data.data.rows.forEach(r => {
              r.checked = false;
            });
            this.cityList = res.data.data.rows;
          }
        });
      },
      //取消选择
      cancelMap() {
        this.showMap = !this.showMap;
      },
      // 确定选择
      sureMap() {
        this.showMap = !this.showMap;
        this.formdata.subjectContent[this.inputLocation] = this.search;
        this.lnglatSure[this.inputLocation] = this.lnglat[this.inputLocation];
      },
      //搜索地址---正向地理编码
      searchSure(value) {
        //地址为空、用户点击选择地点不搜索，
        if(!value ||this.isClickMap){
          this.isClickMap = false;
          return;
        }
        this.geocoder.getLocation(value, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            // result中对应详细地理坐标信息
            this.setMarkerAndCenter(result.geocodes[0].location.lng, result.geocodes[0].location.lat);
            this.lnglat[this.inputLocation] = {
              lng: result.geocodes[0].location.lng,
              lat: result.geocodes[0].location.lat
            }
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: '未找到相关地址'
            })
          }
        })
      },
      //设置选择位置---逆向地理编码
      setLocation(lng, lat) {
        this.setMarkerAndCenter(lng, lat);
        this.lnglat[this.inputLocation] = {lng: lng, lat: lat}
        this.geocoder.getAddress([lng, lat], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            // result为对应的地理位置详细信息
            this.search = result.regeocode && result.regeocode.formattedAddress;
          }
        })
      },
      //设置中心点坐标和标记
      setMarkerAndCenter(lng, lat) {
        if (this.marker) {
          this.marker.setPosition([lng, lat]);
        } else {
          this.marker = new AMap.Marker({
            icon:icon,
            position: [lng, lat]
          });
          this.marker.setMap(this.map);
        }
        this.map.setZoomAndCenter(this.map.getZoom() >= 16 ? this.map.getZoom() : this.map.getZoom() + 1, [lng, lat])
      },
      //地图定位
      choiceLocation(value) {
        document.activeElement.blur();
        this.inputLocation = value || '';
        this.search = this.formdata.subjectContent[this.inputLocation] || '';
        this.showMap = !this.showMap;
        this.map = this.map || new AMap.Map('container' + this.current, {
          resizeEnable: true,
          zoom: 15,
        });
        // AMap.plugin(['AMap.ToolBar', 'AMap.Driving', 'AMap.Geocoder'], () => {//异步同时加载多个插件
        //   this.geocoder = new AMap.Geocoder({});
        this.search && this.searchSure(this.search);
        // });
        this.map.on('click', (ev) => {
          var lnglat = ev.lnglat;
          this.isClickMap = true;
          this.setLocation(lnglat.lng, lnglat.lat);
        });
      },
      //获取标准报销金额
      getAccount() {
        //未选择报销科目不进行验证
        if (!this.formdata.subjectData)
          return
        let data = this.formdata.subjectData;
        let params = {subjectCode: this.formdata.subjectCode,};
        if (data.cityLevel) {
          let {cityLevel} = this.formdata.subjectContent;
          params = {...params, cityLevel: cityLevel};
        }
        if (data.postLevel) {
          let postLevel = this.$store.state.user.userInfo.postBean.level;
          params = {...params, postLevel: postLevel};
        }
        if (data.shipLevel) {
          let {shipLevel} = this.formdata.subjectContent;
          params = {...params, shipLevel: shipLevel};
        }
        if (data.city) {
          let {startCity, endCity} = this.formdata.subjectContent;
          params = {...params, startCity: startCity, endCity: endCity};
        }
        //判断是否存在申请明细
        if (this.exitRequestDetail) {
          if (this.formdata.fillFigure / this.formdata.count > this.exitRequestDetail.figure / this.exitRequestDetail.count) {
            this.$vux.alert.show({
              title: '提醒',
              content: '您输入的金额已超过申请金额,请重新输入！',
              onHide: () => {
                this.formdata.fillFigure = 0
              }
            })
          }
          return
        }
        this.$http.get('/expense/api/standard', {
          params: params
        }).then(res => {
          if (res.data.data.rows && res.data.data.rows.length > 0) {
            if (data.costType == 0) {//按次数、公里匹配报销标准
              let promises = [];
              this.formdata.subjectList.forEach(r => {
                // 如果是startCtiy或者endCity并且没有定位，则获取其经纬度用于定位
                if ((r.key == 'startCity' || r.key == 'endCity') && r.type == 'region') {
                  promises.push(new Promise(resolve => {
                    this.geocoder.getLocation(this.formdata.subjectContent[r.key], (status, result) => {
                      if (status === 'complete' && result.info === 'OK') {
                        // result中对应详细地理坐标信息
                        this.lnglatSure[r.key] = {
                          lng: result.geocodes[0].location.lng,
                          lat: result.geocodes[0].location.lat
                        }
                        resolve();
                      } else {
                        this.$vux.toast.show({
                          type: "warn",
                          text: '未找到相关地址'
                        })
                        resolve();
                      }
                    })
                  }));
                }
              });
              Promise.all(promises).then(resp => {
                let {startCity, endCity} = this.lnglatSure;
                if (!startCity && !endCity) {
                  this.$vux.toast.show({
                    text: '请先输入地点',
                    type: 'warn'
                  })
                  return
                }
                let dis = parseInt(AMap.GeometryUtil.distance([startCity.lng, startCity.lat], [endCity.lng, endCity.lat]) / 1000);
                if (this.formdata.fillFigure / this.formdata.count / dis > res.data.data.rows[0].unitCost) {
                  this.$vux.alert.show({
                    title: '提醒',
                    content: '您输入的金额已超过标准报销金额,请重新输入！',
                    onHide: () => {
                      this.formdata.fillFigure = 0
                    }
                  })
                }
              });
            } else if (data.costType == 1) {//按次数匹配报销标准
              if (this.formdata.fillFigure / this.formdata.count > res.data.data.rows[0].unitCost) {
                this.$vux.alert.show({
                  title: '提醒',
                  content: '您输入的金额已超过标准报销金额,请重新输入！',
                  onHide: () => {
                    this.formdata.fillFigure = 0
                  }
                })
              }
            }
          }
        })
      },
      //弹出拍照界面
      showPopup(imgs,title) {
        imgs && (this.reimbursementImg = imgs);
        this.popupPicTitle = title;
        this.bxdPopup = !this.bxdPopup
      },
      //记录当前选择报销科目
      checkSubject(item = {}) {
        //选择就记录该条数据，取消选择置空记录
        this.currentSubject = item.is ? item : false;
        this.setFalse(this.subjectTree, this.currentSubject ? item.item.data.code : null);
      },
      //记录当前选择地区
      checkCity(item = {}) {
        this.currentCity = item.is ? item : false;
        this.setFalseCity(this.cityTree, this.currentCity ? item.item.code : null);
      },
      //选择报销科目
      checkSureSubject(item) {
        this.isPopup();
        //选择某一项之后内容和列表设置为空
        this.formdata.subjectContent = {};
        this.formdata.subjectList = [];
        if (!item) {
          this.formdata.subjectName = '';
          this.formdata.subjectCode = '';
          return
        }
        this.formdata.subjectName = item.history.reverse().map(r => {
          return r
        }).join('/');
        this.formdata.subjectCode = item.item.data.code;
        this.formdata.subjectData = item.item.data;
        let accountContent = JSON.parse(item.item.data.accountContent);
        let promises = [];
        //费用申请单中存在该明细
        this.exitRequestDetail = false;
        if (this.exitRequestList.length > 0) {
          this.exitRequestList.forEach(r => {
            if (r.subjectCode == this.formdata.subjectCode &&r.status ==1) {
              this.exitRequestDetail = r;
            }
          })
        }
        accountContent.forEach(r => {
          if (r.type === 'select') {
            if (r.key === 'shipLevel') {
              promises.push(new Promise((resolve, reject) => {
                this.$http.get(this.exitRequestDetail ? '/expense/api/shipLevel' : '/expense/api/standard/shipLevel', {
                  params: {
                    subjectCode: this.formdata.subjectCode,
                    noPage: this.exitRequestDetail ? true : false,
                    postLevel: this.exitRequestDetail ? null : this.$store.state.user.userInfo.postBean.level,
                  }
                }).then(res => {
                  if (res.data.data) {
                    if (this.exitRequestDetail) {
                      res.data.data = res.data.data.map(item => {
                        return item.shipLevel;
                      });
                    }
                    r.dict = r.key;//特意处理仓位等级没有dict字段
                    resolve({key: r.dict, value: res.data.data})
                  }
                  else
                    reject()
                })
              }))
            } else {
              promises.push(new Promise((resolve, reject) => {
                this.$http.get('/account/api/dict', {
                  params: {
                    codeLike: r.dict,
                    include: true,
                    noPage: true,
                    fields: 'id,code,name'
                  }
                }).then(res => {
                  if (res.data.data) {
                    res.data.data = res.data.data.map(item => {
                      return item.name;
                    });
                    resolve({key: r.dict, value: res.data.data})
                  }
                  else
                    reject()
                })
              }))
            }
          }
        });
        Promise.all(promises).then(resp => {
          resp.forEach(r => {
            this.formdata.subjectSelect = this.formdata.subjectSelect || {};
            this.formdata.subjectSelect[r.key] = r.value;
          });
          this.formdata.subjectList = JSON.parse(item.item.data.accountContent);
          this.$emit('heightChange')
        });
      },
      //弹出选择框
      isPopup() {
        this.showSubject = !this.showSubject;
      },
      isCityPopup() {
        this.showCity = !this.showCity
      },
      //选择城市
      choiceCity(value) {
        document.activeElement.blur();
        this.isCityPopup();
        this.inputRegion = value || '';
        //暂时先不注释代码
        return
        if (this.cityTree && this.cityTree.length > 0) {
          this.setFalse(this.cityTree, this.formdata.cityTree);
          return;
        }
        this.getCityChild();
      },
      //获取子节点信息
      getCityChild(code = 86) {
        this.$http.get('/account/api/region/child', {params: {code: code}}).then(res => {
            res.data.data.forEach(item => {
              item.open = false;
              item.children = [];
              item.checked = false
            });
            this.cityTree = res.data.data;
          }
        )
      },
      //取消选择
      superiorCity() {
        this.showCity = !this.showCity
      },
      // 确定选择
      subordinateCity(indexData) {
        //当前选择项不是city，则不限制选择城市
        if (this.inputRegion != 'city') {
          this.formdata.subjectContent[this.inputRegion] = indexData.mergerName;
          this.superiorCity();
          return
        }
        //当前存在明细，则不限制选择城市
        if (this.exitRequestDetail) {
          this.formdata.subjectContent[this.inputRegion] = indexData.mergerName;
          this.formdata.subjectContent['cityLevel'] = indexData.level;
          this.superiorCity();
          return
        }
        if (indexData && indexData.cityLevel) {
          this.$http.get('/expense/api/standard/cityLevel', {
            params: {
              subjectCode: this.formdata.subjectCode,
              postLevel: this.$store.state.user.userInfo.postBean.level,
            }
          }).then(dic => {
            if (dic.data.data) {
              if (dic.data.data.includes(indexData.cityLevel)) {
                this.formdata.subjectContent[this.inputRegion] = indexData.mergerName;
                this.formdata.subjectContent['cityLevel'] = indexData.level;
                this.superiorCity()
              } else {
                this.$vux.alert.show({
                  title: '提醒',
                  content: '您选择的城市不符合岗位要求,请重新选择！',
                  onHide: () => {

                  }
                })
              }
            }
          });
        } else {
          this.formdata.subjectContent[this.inputRegion] = indexData.mergerName;
          this.formdata.subjectContent['cityLevel'] = indexData.level;
          this.superiorCity();
          return
        }
      },
      //请求树形数据结构
      choiceSubject(value,$event) {
        document.activeElement.blur();
        if (this.subjectTree && this.subjectTree.length > 0) {
          this.isPopup();
          this.setFalse(this.subjectTree, this.formdata.subjectCode);
          return;
        }
        this.$http.get('/expense/api/expensesubject/tree').then(res => {
            this.isPopup();
            this.subjectTree = res.data.data;
            this.setFalse(this.subjectTree, this.formdata.subjectCode);
          }
        )
      },
      setFalseCity(data, index) {
        data.forEach(item => {
          item.checked = false;
          if (item && (item.code == index)) {
            item.checked = true;
          }
          if (item.children && item.children.length > 0) {
            this.setFalseCity(item.children, index)
          }
        })
      },
      //树形图数据回显
      setFalse(data, index) {
        data.forEach(item => {
          item.checked = false;
          if (item.data && (item.data.code == index)) {
            item.checked = true;
          }
          if (item.children && item.children.length > 0) {
            this.setFalse(item.children, index)
          }
        })
      },
      //取消选择
      superior() {
        this.isPopup()
      },
      // 确定选择
      subordinate() {
        this.checkSureSubject(this.currentSubject);
      }
    },
  }
</script>

<style lang="less">
  ul {
    li {
      .checked {
        border-bottom: 1px solid #E5E5E5;
        .fa {
          color: #2d8cf0;
          font-size: .2rem;
        }
      }
    }
  }

  .costForm {
    .weui-vcode {
      background: #fff;
      .weui-cell__bd {
        padding-right: 10px;
        > input {
          border-right: 1px solid gainsboro;
        }
      }
      .fa-search {
        font-size: 0.18rem;
        color: #3FBCFC;
      }
    }
    .weui-cells {
      .vux-selector.weui-cell_select {
        padding: 5px 10px;
        .weui-select {
          height: 1.5em;
          line-height: 1.5em;
        }
      }
      .weui-cell_select .weui-cell__bd:after {
        border-color: #3FBCFC;
        right: 22px;
      }
      .weui-cell_access {
        .child {
          position: absolute;
          right: 35px;
          font-size: 0.13rem;
        }
        .weui-cell__ft:after {
          border-color: #3FBCFC;
          right: 7px;
        }
      }
    }
    .vux-x-input, .weui-cell_select, .vux-x-textarea {
      .weui-cell__bd {
        padding: 2px;
        border: 0.01rem solid #E5E5E5;
        border-radius: 5px;
      }
    }

    .weui-cell__ft {

      .vux-x-input-right-full {
        margin-left: 0px;
        img {
          height: 12px;
          margin-top: 15px;
          margin-left: -12px;
          margin-right: 5px;
        }
      }
    }
  }
</style>
